<template lang="pug">
  .babyDailyReport
    el-row(:gutter="20")
      el-col(:span="16")
        header
          i-select(
            v-model="classesId"
            :options="classes"
            :props="{ value: 'id', label: 'name'}"
            filterable
            remote
            :remote-method="getClasses"
            :loading="classLoading"
            label="选择班级"
            style="width: 240px"
          )
          el-date-picker(
            v-model="daily"
            type="date"
            placeholder="选择日期"
            range-separator="至"
            @change="dailyChange"
          )
      el-col.tr(:span="8")
        el-date-picker(
          v-model="value2"
          type="month"
          placeholder="选择日期"
          class="mr-10"
        )
        el-button.gradientVertical(size="large" round @click="monthChange") 导出
      el-col(:span="24")
        .childrenList(v-loading="childrenLoading")
          template(v-if="childrenList.length > 0")
            el-button.child(
              v-for="item in childrenList"
              :class="{gradientVertical: childrenId === item.id}"
              @click="childChoseHandle(item.id)"
              :key="item.id"
              size="large"
              round
            ) {{item.name}}
    div.table-empty
      s-table(
        :column="columnsObj",
        :style="{ padding: 0 }",
        :dataPops="list"
        :loading="reportDataLoading"
        :span-method="arraySpanMethod"
      )
        template(slot="type" slot-scope="text, scope")
          div.type(v-if="text==='体温状况'" )
            img(src="~@/assets/twqk.png")
            span {{text}}
          div.type(v-if="text==='睡眠情形'" )
            img(src="~@/assets/smqx.png")
            span {{text}}
          div.type(v-if="text==='如厕状况'" )
            img(src="~@/assets/rzzk.png")
            span {{text}}
          div.type(v-if="text==='饮食方面'" )
            img(src="~@/assets/ysfm.png")
            span {{text}}
          div.type(v-if="text==='用药需求'" )
            img(src="~@/assets/yyxq.png")
            span {{text}}
    //- <div class="quesheng">
    //-   <img src="@/assets/quesheng.png" alt="">
    //-   <span>暂无数据</span>
    //- </div>
    div(v-loading="reportDataLoading")
      el-row(:gutter="200" v-if="reportData.drug&&reportData.drug.length")
        el-col(:span="12")
          //- 用药需求
          .panel
            div.panel-title
              img(src="~@/assets/yyxq.png")
              span {{panels.drug.title}}
            .detail
              p.c_secondary.mb16(v-if="reportData.drug") 在托婴中心托育时段共用药
                b.c_secondary2.ml10.mr10 {{reportData.drug.length}}
                | 次
              p.item(v-for="item in (reportData.drug || [])" :key="item.id")
                span.c_secondary2(style="flex: 1") {{item.eventTime | dateFilter('HH:mm')}} {{item.situation}}
                b.c_secondary2(style="flex: 2")
                  span( v-for="(item, index) in item.medicines" :key="item.id")
                    b.c_66 {{index === 0 ? '': '|'}}{{item.name}}
                span.c_secondary2(style="flex: 1" @click="drugDetailShow(item)") 详情
    drug-dialog(:visible.sync="drug.visible" :info="drug.info")
</template>
<script>
import dayjs from 'dayjs'
import { mapGetters } from 'vuex'
import AImage from '@/components/Basic/Image'
import { getChildrenListByClasses, getClassesByArea } from '@/api/common'
import { columnsObj, dietQuantityType, dietType, panels, pottyColor, pottyState } from './config'
import { dateFilter } from '@/filters'

import { getDailyExport } from '../../api'
import DrugDialog from './components/drugDialog'
import { getMonthLast } from '@/utils/date'

export default {
  name: 'BabyDailyReport',
  components: {
    AImage,
    DrugDialog
  },
  filters: {
    dietFilter (diet) {
      const list = []
      const typeStr = dietType.find((x) => x.value === diet.diet)?.label || ''
      const liquidQuantity = diet.liquidQuantity
      const quantity =
        dietQuantityType.find((x) => x.value === diet.quantity)?.label || ''
      if (typeStr) {
        list.push(typeStr)
      }
      if (liquidQuantity || liquidQuantity === 0) {
        list.push(`喝水：${liquidQuantity}`)
      }
      if (quantity) {
        list.push(`食量：${quantity}`)
      }
      console.log(typeStr, liquidQuantity, quantity)
      return list.join(' | ')
    },
    diaperFilter (val) {
      const colorStr =
        pottyColor.find((x) => x.value === val.color)?.label || ''
      const statusStr =
        pottyState.find((x) => x.value === val.pottyState)?.label || ''
      if (colorStr && statusStr) {
        return `：${[colorStr, statusStr].filter((x) => !!x).join('、')}`
      }
      return ''
    }
  },
  data () {
    return {
      list: [
        {
          type: '体温状况'
        },
        {
          type: '睡眠情形'
        },
        {
          type: '饮食方面'
        },
        {
          type: '如厕状况'
        }
      ],
      columnsObj,
      panels,
      classes: [],
      classesId: '',
      classLoading: false,
      childrenId: '', // 选择宝宝
      childrenList: [],
      childrenLoading: false,
      reportData: {},
      reportDataLoading: false,
      daily: new Date(),

      drug: {
        visible: false,
        info: {}
      },
      value2: new Date()
    }
  },
  computed: {
    ...mapGetters(['curArea'])
  },
  watch: {
    classesId (val) {
      this.childenLoad(val)
    },
    childrenId () {}
  },
  created () {
    this.getClasses()
  },
  methods: {
    /**
     * 计算时间段的数量
     * @param {string} startTime - 开始时间，格式为 "HH:mm"
     * @param {string} endTime - 结束时间，格式为 "HH:mm"
     * @param {number} interval - 每段时间的长度，单位为分钟，默认为15
     * @returns {number} 时间段的数量
     */
    calculateTimeSegments (startTime, endTime, interval = 15) {
      // 创建当天的日期对象
      const startDate = new Date()
      const endDate = new Date()
      // 将开始时间和结束时间设置到日期对象中
      startDate.setHours(parseInt(startTime.split(':')[0], 10))
      startDate.setMinutes(parseInt(startTime.split(':')[1], 10))
      endDate.setHours(parseInt(endTime.split(':')[0], 10))
      endDate.setMinutes(parseInt(endTime.split(':')[1], 10))
      // 计算时间差（分钟）
      const diffInMs = endDate - startDate
      const diffInMinutes = Math.floor(diffInMs / (1000 * 60))
      // 计算段数，向上取整
      return Math.ceil(diffInMinutes / interval)
    },
    arraySpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (row.type === '睡眠情形') {
        const sleep = this.reportData['sleep']
        for (let i = 0; i < sleep.length; i++) {
          const sleepTime = dateFilter(sleep[i]['sleepTime'], 'HH:mm')
          const wakeupTime = dateFilter(sleep[i]['wakeupTime'], 'HH:mm')
          const colspan = this.calculateTimeSegments(sleepTime, wakeupTime)
          if (row.type === '睡眠情形') {
            if (column.label === sleepTime) {
              return {
                rowspan: 1, // 不跨两行
                colspan: colspan === 1 ? 2 : colspan - 1 // 跨列
              }
            }
          }
        }
      }
    },
    setDietFilter (diet) {
      const list = []
      const typeStr = dietType.find((x) => x.value === diet.diet)?.label || ''
      const liquidQuantity = diet.liquidQuantity
      const quantity =
          dietQuantityType.find((x) => x.value === diet.quantity)?.label || ''
      if (typeStr) {
        list.push(typeStr)
      }
      if (liquidQuantity || liquidQuantity === 0) {
        list.push(`喝水：${liquidQuantity}`)
      }
      if (quantity) {
        list.push(`食量：${quantity}`)
      }
      console.log(typeStr, liquidQuantity, quantity)
      return list.join(' | ')
    },
    async getClasses (val = '') {
      const { curArea } = this
      this.classLoading = true
      const res = await getClassesByArea({
        areaId: curArea.areaId,
        name: val,
        category: 1
      })
      this.classes = res || []
      this.classLoading = false
      if (this.classes.length > 0) {
        this.classesId = this.classes[0].id
      }
    },
    // 获取宝宝列表
    childenLoad (classId) {
      const { classes, curArea } = this
      console.log(classes, classId)
      this.childrenLoading = true
      getChildrenListByClasses({ areaId: curArea.areaId, classesId: classId })
        .then((res) => {
          this.childrenList = res || []
        })
        .finally(() => {
          this.childrenLoading = false
        })
    },
    childChoseHandle (id) {
      console.log(id)
      this.childrenId = id
      this.getReportData(id)
    },
    getReportData (childId) {
      const that = this
      const promises = []
      this.reportDataLoading = true
      const daily = dayjs(this.daily).format('YYYY/MM/DD')
      Object.keys(panels).forEach((key) => {
        if (panels[key].fn) {
          promises.push(
            new Promise((resolve) => {
              // if (panels[key].title === "换尿布状况") {
              //   panels[key]
              //     .fn({ childId, daily: daily, diaper: true })
              //     .then((res) => {
              //       resolve({ key, res });
              //     });
              // } else
              if (panels[key].title === '如厕状况') {
                panels[key]
                  .fn({ childId, daily: daily, diaper: false })
                  .then((res) => {
                    resolve({ key, res })
                  })
              } else {
                panels[key].fn({ childId, daily: daily }).then((res) => {
                  resolve({ key, res })
                })
              }
            })
          )
        }
      })
      Promise.all(promises)
        .then((arr) => {
          if (arr && arr.length > 0) {
            const reportData = {}
            for (const item of arr) {
              const { key, res } = item
              reportData[key] = res
            }
            console.log(reportData, 546456)
            that.reportData = reportData
            for (let i = 0; i < that.list.length; i++) {
              if (i === 0) {
                const temperature = reportData['temperature']
                for (let j = 0; j < temperature.length; j++) {
                  that.$set(that.list[i], dateFilter(temperature[j]['eventTime'], 'HH:mm'), ((temperature[j]['temperature'] || 0) / 10) + '℃')
                }
              }
              if (i === 1) {
                const sleep = reportData['sleep']
                for (let j = 0; j < sleep.length; j++) {
                  that.$set(that.list[i], dateFilter(sleep[j]['sleepTime'], 'HH:mm'), sleep[j].remark || '13:00 ~ 15:00')
                }
              }
              if (i === 2) {
                const diet = reportData['diet']
                for (let j = 0; j < diet.length; j++) {
                  that.$set(that.list[i], dateFilter(diet[j]['eventTime'], 'HH:mm'), this.setDietFilter(diet[j]))
                }
              }
              if (i === 3) {
                const toilet = reportData['toilet']
                for (let j = 0; j < toilet.length; j++) {
                  that.$set(that.list[i], dateFilter(toilet[j]['eventTime'], 'HH:mm'), toilet[j]['typeStr'])
                }
              }
            }
            console.log(234224, that.list)
          }
        })
        .finally(() => {
          that.reportDataLoading = false
        })
    },

    dailyChange () {
      if (this.childrenId) {
        this.getReportData(this.childrenId)
      }
    },

    monthChange (res) {
      console.log(this.value2)
      const startTime = dayjs(this.value2).format('YYYY-MM-DD')
      const endTime = getMonthLast(this.value2)
      console.log(startTime)
      console.log(endTime)
      getDailyExport({ startTime, endTime, classId: this.classesId }).then(
        (res) => {
          window.location.href = res
        }
      )
    },

    drugDetailShow (info) {
      console.log(info)
      this.drug = {
        info: info,
        visible: true
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.babyDailyReport {
  display: flex;
  flex-direction: column;
}
.childrenList {
  margin-top: 20px;
  padding: 20px;

  .child {
    margin-bottom: 10px;
    padding: 12px 30px;
  }
}

.panel {
  margin-top: 50px;
  h3 {
    font-size: 17px;
    font-family: PingFang SC;
    font-weight: bold;
    color: #333333;
    margin: 0;
    margin-bottom: 10px;

    > svg {
      vertical-align: middle;
      width: 42px;
      height: 42px;
      margin-right: 5px;
    }
  }

  .detail {
    padding-left: 52px;

    p.item {
      display: flex;
      justify-content: space-between;
      font-size: 15px;
      line-height: 1;
      + p.item {
        margin-top: 20px;
      }
    }
  }
}
.type{
  font-family: Source Han Sans SC, Source Han Sans SC;
  font-weight: bold;
  font-size: 16px;
  color: #000;
  line-height: 19px;
  text-align: left;
  font-style: normal;
  text-transform: none;
  display: flex;
  flex-direction: column;
  align-items: center;
  img{
    width: 32px;
    height: 32px;
    margin-bottom: 8px;
  }
}
.panel-title{
  font-family: Source Han Sans SC, Source Han Sans SC;
  font-weight: bold;
  font-size: 16px;
  color: #000;
  font-style: normal;
  text-transform: none;
  display: flex;
  align-items: center;
  img{
    width: 32px;
    height: 32px;
  }
}
.quesheng{
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
  img{
    margin-bottom: 12px;
  }
}
</style>
